package rjeutsky.database.jpa;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import rjeutsky.database.jpa.models.JPAPublication;
import rjeutsky.models.Publication;

public class JPAPublicationRepository extends BaseCRUDDomainRepository<Publication> {

	public JPAPublicationRepository(SessionFactory sessionFactory) {
		super(sessionFactory);
	}
	
	@Override
	public List<Publication> query() throws SQLException {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		@SuppressWarnings("unchecked")
		List<Publication> publications =  JPAPublication.getPublications(session.createQuery("from JPAPublication").list());
		
		session.getTransaction().commit();
		session.close();
		
		return publications;
	}

	@Override
	public void create(Publication item) throws SQLException {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		JPAPublication publication = new JPAPublication();
		publication.setName(item.getName());
		publication.setPrice(item.getPrice());
		session.save(publication);
		item.setId(publication.getId());
		
		session.getTransaction().commit();
		session.close();
	}

	@Override
	public Publication read(long id) throws SQLException {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		Publication publication = null;
		
		JPAPublication jpaPublication = (JPAPublication) session.get(JPAPublication.class, id);
		if (jpaPublication != null) {
			publication = jpaPublication.getPublication();
		}
		
		session.getTransaction().commit();
		session.close();
		return publication;
	}

	@Override
	public void update(Publication item) throws SQLException {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		JPAPublication publication = JPAPublication.getJPAPublication(session, item);
		if (publication != null) {
			publication.setName(item.getName());
			publication.setPrice(item.getPrice());
		}
		
		session.getTransaction().commit();
		session.close();
	}

	@Override
	public void delete(long id) throws SQLException {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		JPAPublication publication = (JPAPublication) session.get(JPAPublication.class, id);
		if (publication != null) {
			session.delete(publication);
		}
		
		session.getTransaction().commit();
		session.close();
	}

}
